#!/usr/bin/env python
# coding: UTF-8
#filename: D:/workspace/python/demo/mybatishandler/XmlUtil.py
from mybatishandler import CommonConstants
from mybatishandler.CRUDXML import CRUDXML
from mybatishandler.Mapper import Mapper
from mybatishandler.ResultMap import ResultMap
from mybatishandler.SQLGenerater import InsertSQLGenerater, \
    UpdateSQLGenerater, UpdateSQLGenerater
from xml.dom import minidom
import sqlparse
import xml.etree.ElementTree as ET


'''
Created on 2013-7-12 下午6:02:13

@author: zhanghu
'''

class XmlUtil(object):
    '''
    classdocs
    '''


    def __init__(self, fileName):
        '''
        Constructor
        '''
        if fileName is None:
            if CommonConstants.DEBUG:
                print 'error file name is null'
            return;
        
        self.et = ET.parse(fileName)
        self.root = self.et.getroot()
        self.fileName = fileName
        
    # TODO 可能不需要
    def write(self, fileName, xmlStr):
        if fileName is None or xmlStr is None:
            return;
        
        root = self.root
        
        root.append()
        
    
    def wrapper(self, crud_xml):
        if crud_xml is None:
            return
        
        element = ET.Element(crud_xml.type)
        element.set('id', crud_xml.id)
        element.set('BaseResultMap', crud_xml.resultMap)
        element.set('parameterType', crud_xml.parameterType)
        element.text = crud_xml.sql
        
        return element
    
    def appendElement(self, element):
        if element is None:
            return
        self.root.append(element)
        
    def persistent(self):
        self.et.write(self.fileName + '.bak', 'utf-8')
    
    def buildMapper(self):
        if self.root is None:
            return
        
        # 结果
        mapper = Mapper()
        
        # 获得文件描述
        elements = self.root.find('resultMap')
        
        # 构建resultMap属性
        resultMap = ResultMap()
        for key, value in elements.attrib.items():
            if key == 'id':
                resultMap.id = value
            elif key == 'type':
                resultMap.type = value
            else:
                print '未处理的属性类型[%s:%s]' % (key, value)
            
        # 构建resultMap的子元素
        for e in elements._children :
            #TOOD 增加flag
            if e.tag == 'id':
                resultMap.primaryKey = e.attrib
                continue
                
            resultMap.results.append(e.attrib)
            
        # 构建resultMap完成
        mapper.setResultMap(resultMap)
        
        # 构建select
        
        # 构建update
        
        # 构建insert
        
        # 构建delete
        
        return mapper
    
    def fomatTree(self):
        """格式化XML的内容,用于输出，保存XML时并不需要"""
        root_str = ET.tostring(self.root, 'UTF-8')
        reparse = minidom.parseString(root_str)
        return reparse.toprettyxml(indent="  " , encoding="utf-8")
    
    def formatAllSql(self):
        return [sqlparse.format(sql) for sql in self.getAllSQL()]
        
    
    def getAllSQL(self):
        # 可以简单表示
        # 存在\n字符
        result = []
        
        result.append(self.root.findall(CommonConstants.SQL_TYPE_INSERT))
        result.append(self.root.findall(CommonConstants.SQL_TYPE_DELETE))
        result.append(self.root.findall(CommonConstants.SQL_TYPE_UPDATE))
        result.append(self.root.findall(CommonConstants.SQL_TYPE_SELECT))
        
        res = []
        
        for elements in result:
            for element in elements:
                text = element.text
                if text is not None or len(text.strip()) != 0 or text == '\n' :
                    res.append(element.text)
                    
        return res
       
    
    

if __name__ == '__main__':
    xml = XmlUtil('d:\\workspace\\python\\demo\\com\\jd\\py\\demo\\xml\\DistributeTempMapper.xml')
    
#    sg = SelectSQLGenerater(MSSQLDialect(), xml.buildMapper())
#    sg = InsertSQLGenerater(xml.buildMapper())
    sg = UpdateSQLGenerater(xml.buildMapper())
    
    sg.tableName = 'distributetemp';
    sg.setMainFeilds(['*'])
#    sg.mapper = xml.buildMapper();
#    sg.mainFields = ['ID', 'ORDERID', 'SEP_STATUS', 'OPERATORID']
    
    xml.appendElement(xml.wrapper(CRUDXML('testSelect', 'java.lang.Integer', 'java.lang.String', 'select', sg.generate())))
    
    formatStr = xml.fomatTree()
    
    
#    print formatStr
    
    
#    formatter = xmlformatter.formatter.Formatter()
    # file
#    print formatter.format_file('d:\\workspace\\python\\demo\\com\\jd\\py\\demo\\xml\\DistributeTempMapper.xml')
    
#    f = open('d:\\workspace\\python\\demo\\com\\jd\\py\\demo\\xml\\DistributeTempMapper.xml.text', 'w');
#    
#    for str in formatStr:
#        f.write(str)
#        
#    f.close()
    
    xml.persistent()

